<template>
  <div v-loading="loading">
    <el-row>
      <el-col :span="24">
        <div class="searchData_tit">
          <el-input v-model="keyword" :placeholder="$t('请输入')" class="input-with-select" @keyup.enter.native="searchData('query')">
            <el-button slot="append" type="primary" icon="el-icon-search" @click="searchData('query')" />
          </el-input>
        </div>
      </el-col>
    </el-row>
    <div class="list-table">
      <el-row>
        <el-col :span="4">
          <div class="tree-div">
            <!--  -->
            <el-tree
              ref="tree"
              :data="menuData"
              highlight-current
              :expand-on-click-node="false"
              lazy
              node-key="id"
              :load="loadTreeChild"
              :current-node-key="currentNodeKey"
              :default-expanded-keys="expansionLevel"
              @node-click="handleNodeClick"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node" style="font-size: 14px;" @click="getLevel(node)">
                <span>{{ $t( node.label.split("(")[0]) }}</span>
                <span>(</span>{{ data.count }}<span>)</span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="20" class="contentBuss">
          <!--最外层的循环是业务名称循环，也就是将查询出来的所有数据，根据项目/基金名称进行了分组，
        先展示项目/基金名称，下面的数据根据名称和ID进行匹配展示，第二层匹配展示数据来源（如：基本信息、重大事项、团队成员等）
        第三层匹配展示实际数据结果 -->
          <div v-if="dataType === 'deal' || dataType === 'fund' || dataType === '' || dataType === 'company'">
            <div v-for="(bussValue,bussKey) in bussMap" :key="bussKey" class="contentKey" style="">
              <!--data 是一个Map集合，里面存着字段名称（key）==> 字段值(value) -->
              <h3 class="topTit" style="color: #3497e2;">
                <router-link
                  target="_blank"
                  :to="{path: bussValue.split('_')[2]}"
                  class="link_a"
                >{{ bussValue.split("_")[0] }}</router-link>
              </h3>
              <!-- 第二层，暂时数据来源匹配 -->
              <div v-for="(souValue,souKey) in souMap" :key="souKey" class="souMap">
                <!-- 展示数据来源，如（基本信息、重大事项、团队成员等）-->
                <div v-if="souValue.split('_')[1] === bussValue.split('_')[1]">
                  <h5 class="samllTit" style="">{{ $t(souValue.split('_')[2]) }}</h5>
                  <!--第三层循环，展示实际数据，需要对业务ID和数据来源进行匹配展示 -->
                  <div v-for="(data,index) in resultData" :key="index" class="resultData" style="" @click="openUrl(data)">
                    <!--基金和项目-->
                    <div v-if=" (data.par_buss_type === 'deal' || data.par_buss_type === 'fund' || data.par_buss_type === 'company') && bussValue.split('_')[1] === data.par_buss_id && souValue.split('_')[2] === data.par_source " class="souValue">
                      <div v-for="(value,key) in data" :key="key" class="row-data">
                        <span v-if="value!==''&&value!==null&&key.indexOf('par_')<0" class="span">
                          <span v-html="$t(key.substring(key.lastIndexOf('_') + 1))" />:
                          <span class="value" v-html="$t(value)" />
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!--新闻舆情-->
          <div v-else-if="dataType === 'news'">
            <!--第一层展示新闻标题-->
            <div v-for="(data,index) in resultData" :key="index" class="contentKey" style="">
              <h3 class="topTit" style="color: #3497e2;">
                <a
                  class="link_a"
                  @click="openNews(data.par_news_url)"
                  v-html="data.news_title"
                />
              </h3>
              <!-- 第二层，展示新闻信息，点击新闻信息，打开新闻 -->
              <div class="souMap">
                <!--第三层循环，展示实际数据，需要对业务ID和数据来源进行匹配展示 -->
                <div class="resultData" style="" @click="openNews(data.par_news_url)">
                  <div class="souValue">
                    <div v-for="(value,key) in data" :key="key" class="row-data">
                      <span v-if="value!==''&&value!==null&&key.indexOf('par_')<0&&key!=='news_title'" class="span">
                        <span v-html="key.substring(key.lastIndexOf('_') + 1)" />：
                        <span class="value" v-html="value" />
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!--文件 -->
          <div v-else-if="dataType === 'file'">
            <!--第一层展示附件名称-->
            <div v-for="(data,index) in resultData" :key="index" class="contentKey" style="">
              <h3 class="topTit" style="color: #3497e2;">
                <a
                  class="link_a"
                  @click="onlinePreview(data.par_id)"
                  v-html="data.file_name"
                />
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <el-button
                  v-if="configDownloadEnabled"
                  size="small"
                  type="text"
                  icon="el-icon-download"
                  @click="download(data.par_id)"
                >{{ $t('下载') }}</el-button>
              </h3>
              <!-- 第二层，展示文档信息 -->
              <div class="souMap">
                <!--第三层循环，展示实际数据，需要对业务ID和数据来源进行匹配展示 -->
                <div class="resultData" style="" @click="onlinePreview(data.par_id)">
                  <div class="souValue">
                    <div v-for="(value,key) in data" :key="key" class="row-data">
                      <span v-if="value!==''&&value!==null&&key.indexOf('par_')<0&&key!=='file_name'" class="span">
                        <span v-html="key.substring(key.lastIndexOf('_') + 1)" />：
                        <span class="value" v-html="value" />
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="searchData('')"
      />
    </div>

    <div v-show="showBtn" slot="footer" class="dialog-footer" style="text-align: center; margin-top: 20px;">
      <el-button icon="el-icon-refresh" type="primary" size="mini" @click="initElastic">{{ $t('初始化数据') }}</el-button>
    </div>

    <el-dialog :title="title" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <component :is="formPath" ref="formPath" />
    </el-dialog>

    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>
<script>
  import { initData, searchData, loadTreeChild } from '@/api/elastic/elastic'
  import { getAsyncComponent } from '@/utils'
  import { downLoadFileOpen } from '@/utils/zipdownload'
  export default {
    name: 'SearchData',
    data() {
      return {
        // 遮罩层
        loading: false,
        // 存放左边的菜单选项
        menuData: [],
        // 展示右边的数据
        resultData: [],
        // 业务类型集合
        bussMap: [],
        // 业务来源集合
        souMap: [],
        // 查询数据参数
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        // 关键字
        keyword: this.$route.query.keyword,
        currentNodeKey: '',
        expansionLevel: [],
        // 打开页面路径
        formPath: '',
        // 打开页面传参
        formParams: {},
        // 数据类型
        dataType: '',
        // 表单是否open
        formOpen: false,
        // 表单title
        title: '',
        // 总条数
        total: 0,
        showBtn: false,
        flag: true,
        level: 1,
        // 全局下载开关
        configDownloadEnabled: true
      }
    },
    watch: {
      '$route': function() {
        this.keyword = this.$route.query.keyword
        // 执行数据更新查询
        this.searchData('query')
      },
      currentNodeKey(id) {
        if (id) {
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(id)
            this.$nextTick(() => {
                document.querySelector('.is-current').firstChild.click()
            })
          })
        }
      }
    },
    created() {
      this.searchData('query')
    //   this.getConfigKey('es_switch').then(res => {
    //     if (res.msg === '1') {
    //       this.showBtn = true
    //     } else {
    //       this.showBtn = false
    //     }
    // })
      // 全局下载开关
      this.getConfigKeyToDownload('enable_download').then(response => {
        this.configDownloadEnabled = (response.msg === 'true')
      })
    },
    methods: {
      getLevel(node) {
        this.level = node.level
      },
      // 点击节点，加载节点数据
      handleNodeClick(data) {
        if (data.id) {
          this.currentNodeKey = data.id
          this.expansionLevel = [data.id]
        }
        this.loading = true
        this.queryParams.dataType = data.dataType
        this.queryParams.pageNum = 1
        this.dataType = data.bussType ? data.bussType : data.dataType
        searchData(this.queryParams).then(res => {
          if (res.datas) {
            // 业务名称数据集合
            this.bussMap = res.datas.bussMap
            // 业务来源数据集合
            this.souMap = res.datas.souMap
            // 右边所有数据结果
            this.resultData = res.datas.tableDataInfo.rows
            this.total = res.datas.tableDataInfo.total
            if (this.resultData !== null && this.resultData !== undefined) {
              this.resultData.forEach(item => {
                this.heightTxt(item)
              })
            }
          }
          this.loading = false
        })
      },
      // 下载
      download(id) {
        downLoadFileOpen(id)
      },
      // 懒加载数据
      loadTreeChild(node, resolve) {
        if (node.level === 0 || node.data.dataType === 'news' || node.data.dataType === 'file') {
          return resolve([])
        }
        this.queryParams.dataType = node.data.dataType
        this.queryParams.bussType = node.data.bussType
        this.queryParams.keyword = this.keyword
        // this.loading = true
        loadTreeChild(this.queryParams).then(res => {
          if (res.datas.leftList !== undefined) {
            resolve(res.datas.leftList)
          } else {
            resolve([])
          }
        })
      },
      // 初始化数据
      initElastic() {
        this.loading = true
        initData().then(res => {
          this.loading = false
          this.msgSuccess(res.msg)
        })
      },
      // 查询数据 参数：区别是查询还是分页
      searchData(type) {
        this.queryParams.keyword = this.keyword
        // 判断，如果点击的是查询按钮，那么将当前的页码置为1
        if (type === 'query') {
          this.queryParams.pageNum = 1
          this.queryParams.dataType = ''
          this.flag = true
        }
        this.loading = true
        searchData(this.queryParams).then(res => {
          // 左侧树形机构数据集合
          if (this.flag) {
            this.menuData = res.datas.leftList
            if (this.menuData.length > 0 && this.menuData[0].id) {
              this.expansionLevel = [this.menuData[0].id]
              this.currentNodeKey = this.menuData[0].id
            }
            this.flag = false
          }
          // 业务名称数据集合
          this.bussMap = res.datas.bussMap
          // 业务来源数据集合
          this.souMap = res.datas.souMap
          // 右边所有数据结果
          this.resultData = res.datas.tableDataInfo.rows
          // 查询出来的总条数
          this.total = res.datas.tableDataInfo.total
          // 默认展示的数据类型
          if (this.level === 1) {
            this.dataType = res.datas.dataType
          }
          // 设置高亮显示关键字
          if (this.resultData !== null && this.resultData !== undefined) {
            this.resultData.forEach(item => {
              this.heightTxt(item)
            })
          }
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      // 高亮显示 item ==> Map集合
      heightTxt(item) {
        // 高亮显示关键字，并且截取过长的字符串
        if (this.keyword !== '') {
          var keywordArray = this.keyword.split(/\s+/)
          keywordArray.forEach(strItem => {
            if (strItem !== '') {
              for (var key in item) {
                if (key.indexOf('par_') < 0) {
                  var val = item[key]
                  if (val !== null && val !== '' && val !== undefined) {
                    // 1、找到第一次出现关键字的地方
                    var idx = val.indexOf(strItem)
                    idx = parseFloat(idx)
                    var s_idx = 0
                    var e_idx = val.length
                    if (idx < 40) {
                      e_idx = (idx + 40) > e_idx ? e_idx : (idx + 40)
                    } else {
                      s_idx = idx - 40
                      e_idx = (idx + 40) > e_idx ? e_idx : (idx + 40)
                    }
                    var txt = val.substring(s_idx, e_idx)
                    if (txt !== val) {
                      txt += '...'
                    }
                    txt = txt.replace(new RegExp(strItem.trim(), 'g'), '<span class=\'eslight\'>' + strItem + '</span>')
                    item[key] = txt
                  }
                }
              }
            }
          })
        }
      },
      // 打开链接
      openUrl(data) {
        if (data.par_data_type === 'deal_base' || data.par_data_type === 'fund_base' || data.par_data_type === 'company_base') {
          var routeData = this.$router.resolve({ path: data.par_data_url })
          window.open(routeData.href, '_blank')
          // this.$router.push({ path: data.par_data_url })
        } else {
          var formData = {}
          if (data.par_data_type === 'fund_terms') {
            // 基金关键条款，加载form页面的init方法
            formData = { 'id': data.par_buss_id }
          } else {
            formData = { 'id': data.par_id }
          }
          var dataUrl = data.par_data_url
          this.importFormPath('@/views/' + dataUrl, formData)
          this.formOpen = true
          this.title = data.par_source
          this.$nextTick(() => {
            this.loadComponent()
          })
        }
      },
      // 引入流程申请单组件
      importFormPath(formPath, data) {
        this.formPath = getAsyncComponent(formPath)
        this.formParams = data
      },
      // 加载组件
      loadComponent() {
        this.$bus.$on('async_done', () => {
          this.$nextTick(() => {
            this.$refs.formPath && this.$refs.formPath.init(this.formParams)
            // 隐藏保存按钮
            this.$refs.formPath.btnHide = true
          })
        })
      },
      // 打开新闻链接
      openNews(newUrl) {
        if (newUrl.indexOf('http://') !== -1) {
          window.open(newUrl)
        } else if (newUrl.indexOf('https://') !== -1) {
          window.open(newUrl)
        } else {
          window.open('http://' + newUrl)
        }
      },
      // 预览附件
      onlinePreview(id) {
        this.$refs.OnlinePreview.onlinePreviewFile(id)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .tree-div{

  }
  .contentBuss{
    border-left: 1px solid #ddd;
    padding-left: 20px;
    .contentKey{
      border: 1px solid #eee;
      border-radius: 10px;
      padding: 15px;
      margin-bottom: 15px;
      h3{
        margin: 0;
        font-size: 16px;
        margin-bottom: 10px;
      }
      .souMap{
        .samllTit{
          margin: 0;
          font-size: 14px;
        }
        .resultData{
          margin: 10px 0 0;
          line-height: 25px;
          .row-data{
            span{
              &:first-child{
                color: #666666;
              }
              .valuev{
                color: #000;
              }
            }
          }
          .souValue{
            padding: 5px 10px;
            background: #f9f9f9;
            border-radius: 5px;
            &:hover{
              background: #e2e2e2;
              cursor: pointer;
            }
            .row-data {
              font-size: 13px;
              display: inline-block;
              .span{
                margin-right: 20px;
              }
            }
          }
        }
      }
    }
  }

</style>
